package com.example.demo.service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

@Service
public class EmailService {

	@Value(value = "${spring.mail.username}")
	private String mailUsername;

	@Autowired
	JavaMailSender mailSender;

	@Autowired
	FreeMarkerConfigurer freeMarkerConfigurer;

	/**
	 * 
	 * @param subject
	 *            主题
	 * @param toEamil
	 *            收件人
	 * @param content
	 *            内容
	 */
	public void sendEmail(String subject, String toEamil, String content) {
		// SimpleMailMessage mailMessage = new SimpleMailMessage();
		// mailMessage.setFrom(mailUsername);
		// mailMessage.setSubject(subject);
		// mailMessage.setTo(toEamil);
		// mailMessage.setText(content);

		MimeMessage message = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(mailUsername);
			helper.setSubject(subject);
			helper.setTo(toEamil);
			helper.setText(content);

			// 附件
			helper.addAttachment("Accp课程调整计划.xls", new File("src/main/resources/static/Accp课程调整计划.xls"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		mailSender.send(message);
		System.out.println("发送邮件成功!");
	}

	public void sendEmailToTlp(String subject, String toEamil, String content) {
		MimeMessage message = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(mailUsername);
			helper.setSubject(subject);
			helper.setTo(toEamil);

			Map<String, Object> map = new HashMap<>();
			map.put("username", content);
			Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email/register.tlp");
			
			String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
			System.out.println(html);
			
			helper.setText(html,true);
		} catch (Exception e) {
			e.printStackTrace();
		}

		mailSender.send(message);
		System.out.println("发送邮件成功!");
	}
}
